#include "Borrower_t.h"
#include "Book_t.h"
#include <sstream>

unsigned long Borrower_t::ids = 1;

Borrower_t::Borrower_t(std::string name)
	: m_name(name), m_waitingCount(0)
{
	if(m_name.compare("") == 0)
		m_id = 0;
	else
		m_id = Borrower_t::ids++;
}

Borrower_t::~Borrower_t()
{

}

int Borrower_t::addBorrowed(Book_t* const book)
{
	// check if book is already borrowed by the reader	
	if(alreadyBorrowed(book))
		return -1;

	// check if the book has available copies
	if(book->isAvailable())
	{
		m_borrowed.push_back(book);
		return 1;
	}

	m_waitingCount++;
	return 0;
}

bool Borrower_t::alreadyBorrowed(Book_t* const book) const
{
	borrowedList::const_iterator it = m_borrowed.begin();
	while(it != m_borrowed.end())
	{
		if(book == *it)
			return true;
		it++;
	}

	return false;
}

int Borrower_t::returnBook(Book_t* book)
{
	// check if the boorower actually borrowed the book
	if(!alreadyBorrowed(book))
		return -1;
	
	m_borrowed.remove(book);

	// check if other readers are waiting for the book
	if(book->isSomeoneWaiting())
		return 0;

	return 1;
}

std::string Borrower_t::borrowerReport() const
{
	std::ostringstream os;
	os << *this << std::endl;
	os.fill('-');
	os.width(m_name.length()*5);
	os << "-";
	os << std::endl;

	borrowedList::const_iterator it = m_borrowed.begin();
	int i=1;
	while(it != m_borrowed.end())
	{
		os << i << ". " << (*it)->name() << std::endl;
		it++;
		i++;
	}

	os << std::endl;
	return os.str();
}

bool Borrower_t::operator==(const Borrower_t* other) const
{
	return m_id == other->id();
}


std::ostream& operator<<(std::ostream& os, const Borrower_t& other)
{
	os << "Reader: " << other.m_name <<" (ID=" << other.m_id << ")";

	return os;
}